<?php

    /**
    * This is the model class for table "movie".
    *
    * The followings are the available columns in table 'movie':
    * @property string $id
    * @property string $name
    * @property string $name_en
    * @property string $image
    * @property string $country_id
    * @property string $actor
    * @property string $director
    * @property string $year
    * @property string $desc
    * @property string $content
    * @property string $type
    * @property integer $is_cinema
    * @property string $manager_id
    * @property string $fb_like_count
    * @property string $fb_comment_count
    * @property integer $is_hot
    * @property integer $is_completed
    * @property integer $is_enable
    * @property integer $is_hd
    * @property string $created
    * @property integer $episode
    * @property string $episode_update_time
    * @property string $view
    * @property string $view_week
    * @property string $view_month
    *
    * The followings are the available model relations:
    * @property Country $country
    * @property Manager $manager
    * @property Cat[] $cats
    * @property Link[] $link
    */
    class Movie extends CActiveRecord
    {

        public $upload_method = 'file';
        public $image_file;
        public $image_url;

        public $server;
        public $link;

        /**
        * Returns the static model of the specified AR class.
        * @param string $className active record class name.
        * @return Movie the static model class
        */
        public static function model($className=__CLASS__)
        {
            return parent::model($className);
        }

        /**
        * @return string the associated database table name
        */
        public function tableName()
        {
            return 'movie';
        }

        /**
        * @return array validation rules for model attributes.
        */
        public function rules()
        {
            // NOTE: you should only define rules for those attributes that
            // will receive user inputs.
            return array(
                array('name, country_id, year, cats', 'required'),
                array('is_cinema, is_hot, is_completed, is_enable, is_hd, episode', 'numerical', 'integerOnly'=>true),
                array('name, name_en, image, actor, director', 'length', 'max'=>255),
                array('desc', 'length', 'max'=>500),
                array('country_id, manager_id, fb_like_count, fb_comment_count, view, view_week, view_month', 'length', 'max'=>10),
                array('year', 'length', 'max'=>4),
                array('type', 'length', 'max'=>6),
                array('content, desc, trailer', 'safe'),

                array('image_file', 'file', 'allowEmpty' => true),
                array('image_file', 'file', 'types'=>'jpg, gif, png', 'allowEmpty' => true),

                array('image_url', 'url', 'allowEmpty' => true, 'on' => 'update'),
                array('upload_method', 'checkUpload', 'on' => 'create'),  

                // The following rule is used by search().
                // Please remove those attributes that should not be searched.
                array('id, name, name_en, image, country_id, actor, director, year, desc, content, type, is_cinema, manager_id, fb_like_count, fb_comment_count, is_hot, is_completed, is_enable, is_hd, created, episode, episode_update_time, view, view_week, view_month', 'safe', 'on'=>'search'),
            );
        }

        public function checkUpload($attribute, $params)
        {
            $post = $_POST['Movie'];

            $uv = new CUrlValidator;
            $urlValidate = $uv->validateValue($post['image_url']);

            if($post['upload_method'] == 'url'){
                if(!$post['image_url'] || ($post['image_url'] && !$urlValidate)){
                    $this->addError('upload_method', 'Đường dẫn URl ảnh phải đúng định dạng');    
                }
            } elseif($post['upload_method'] == 'file' && !$_FILES['browse_file']['size']){
                $this->addError('upload_method', 'Bạn cần chọn 1 ảnh để upload');
            }
        }


        /**
        * @return array relational rules.
        */
        public function relations()
        {
            // NOTE: you may need to adjust the relation name and the related
            // class name for the relations automatically generated below.
            return array(
                'country' => array(self::BELONGS_TO, 'MovieCountry', 'country_id'),
                'manager' => array(self::BELONGS_TO, 'Manager', 'manager_id'),
                'cats' => array(self::MANY_MANY, 'MovieCat', 'movie_in_cat(movie_id, cat_id)'),
                'links' => array(self::HAS_MANY, 'MovieLink', 'movie_id'),
            );
        }

        /**
        * @return array customized attribute labels (name=>label)
        */
        public function attributeLabels()
        {
            return array(
                'id' => 'ID',
                'name' => 'Tên phim',
                'name_en' => 'Tên tiếng anh',
                'image' => 'Poster',
                'country_id' => 'Quốc gia',
                'actor' => 'Diễn viên',
                'director' => 'Đạo diễn',
                'year' => 'Năm sản xuất',
                'desc' => 'Mô tả ngắn',
                'content' => 'Chi tiết phim',
                'type' => 'Loại phim',
                'is_cinema' => 'Là phim chiểu ở rạp',
                'manager_id' => 'Manager',
                'fb_like_count' => 'Fb Like Count',
                'fb_comment_count' => 'Fb Comment Count',
                'is_hot' => 'Là phim HOT',
                'is_completed' => 'Đã hoàn thành',
                'is_enable' => 'Hiển thị',
                'is_hd' => 'Là phim HD',
                'created' => 'Ngày đăng',
                'episode' => 'Số tập',
                'episode_update_time' => 'Episode Update Time',
                'view' => 'View',
                'view_week' => 'View Week',
                'view_month' => 'View Month',
                'cats' => 'Thể loại phim',
            );
        }

        /**
        * Retrieves a list of models based on the current search/filter conditions.
        * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
        */
        public function search()
        {
            // Warning: Please modify the following code to remove attributes that
            // should not be searched.

            $criteria=new CDbCriteria;

            $criteria->compare('id',$this->id);
            $criteria->compare('name',$this->name,true);
            $criteria->compare('name_en',$this->name_en,true);
            $criteria->compare('image',$this->image,true);
            $criteria->compare('country_id',$this->country_id,true);
            $criteria->compare('actor',$this->actor,true);
            $criteria->compare('director',$this->director,true);
            $criteria->compare('year',$this->year,true);
            $criteria->compare('desc',$this->desc,true);
            $criteria->compare('content',$this->content,true);
            $criteria->compare('type',$this->type,true);
            $criteria->compare('is_cinema',$this->is_cinema);
            $criteria->compare('manager_id',$this->manager_id,true);
            $criteria->compare('fb_like_count',$this->fb_like_count,true);
            $criteria->compare('fb_comment_count',$this->fb_comment_count,true);
            $criteria->compare('is_hot',$this->is_hot);
            $criteria->compare('is_completed',$this->is_completed);
            $criteria->compare('is_enable',$this->is_enable);
            $criteria->compare('is_hd',$this->is_hd);
            $criteria->compare('created',$this->created,true);
            $criteria->compare('episode',$this->episode);
            $criteria->compare('episode_update_time',$this->episode_update_time,true);
            $criteria->compare('view',$this->view,true);
            $criteria->compare('view_week',$this->view_week,true);
            $criteria->compare('view_month',$this->view_month,true);

            if($this->cats){
                $criteria->with = array(
                    'cats' => array(
                        'alias' => 'cat',
                    ),
                );
                $criteria->compare('cat.cat_id',$this->cats);
            }

            $sort = new CSort;
            $sort->defaultOrder = 'id DESC';
            $sort->attributes = array(
                'name'=> FALSE,
                //                'name_en'=> 'name_en',
                //                'created' => array(
                //                    'asc'=>'created',
                //                    'desc'=>'created DESC',
                //                ),
            );

            return new CActiveDataProvider($this, array(
                    'criteria'=>$criteria,
                    'sort' => $sort,
                ));
        }

        public function getTypeData(){
            return array(
                'SHORT' => 'Phim lẻ',
                'SERIES' => 'Phim bộ',
            );
        }
        public function getTypeLabel(){
            return $this->typeData[$this->type];
        } 

        public function getHotData(){
            return array(
                '1' => 'HOT',
                '0' => 'Not HOT',
            );
        }
        public function getHotLabel(){
            return $this->is_hot ? 'HOT' : '';
        } 

        public function getEnableData(){
            return array(
                '1' => 'Hiện',
                '0' => 'Ẩn',
            );
        }


        public function getEnableLabel(){
            return $this->enableData[$this->is_enable];
        } 

        public function getCatsLabel(){
            $cats = array();
            foreach($this->cats as $cat){
                $cats[] = $cat->name;        
            }
            return "<ul><li style='margin-left: 10px'>".implode("</li><li style='margin-left: 10px'>", $cats)."</li></ul>";
        }

        public function getUrl($type = 'view', $params = array()) {
            $params['year'] = $this->year;
            $params['alias'] = $this->alias;
            //$params['alias_en'] = $this->alias_en;
            return Yii::app()->createAbsoluteUrl('/movie/movie/' . $type, $params);
        }
        public function getAdminUrl($type = 'view') {
            return Yii::app()->createUrl('/admin/movie/' . $type, array("id" => $this->id));
        }

        public function getImageUrl($thumb = FALSE){
            $imgConf = Yii::app()->params->movie_img;
            $thumb = $thumb ? '_thumb' : '';
            return Yii::app()->controller->baseUrl.'/'.$imgConf['path'].$this->id."/{$this->image}{$thumb}.jpg";
        }

        public function getImageThumbUrl(){
            return $this->getImageUrl(TRUE);
        }

        public function getCatLinks(){
            $array = array();
            foreach($this->cats as $cat){
                $array[] = CHtml::link($cat->name, $cat->url, array('title' => 'Phim '.$cat->name));
            }
            return implode(', ', $array);
        }

        public function getNameFull(){
            return CHtml::encode($this->name) . ($this->name_en ? ' - '.CHtml::encode($this->name_en) : ''); 
        }
        public function getNameEncode(){
            return CHtml::encode($this->name); 
        }
        
        public function getTrailerIframe(){
            $id = preg_replace('{.+watch\?v=(.{11}).*}', '$1', trim($this->trailer));
            return "http://www.youtube.com/embed/{$id}?rel=0";
        }
        
        
        public function getServerLinks(){
            $data = array();
            foreach($this->links as $i => $server){
                $alias = TextParser::toSEOString($server->server);
                $data[$alias]['name'] = $server->server;
                if(count($server->links) == 1){
                    $i = 1;
                    foreach($server->links[1] as $link){
                        $data[$alias]['links'][$i] = array(
                            'url' => $link,
                            'url_redirect' => Yii::app()->createAbsoluteUrl('/movie/movie/redirect', array(
                                    'year' => $this->year, 
                                    'alias' => $this->alias, 
                                    'server' => $alias, 
                                    'part' => $i
                                )),
                            'url_web' => Yii::app()->createAbsoluteUrl('/movie/movie/view', array(
                                    'year' => $this->year, 
                                    'alias' => $this->alias, 
                                    'server' => $alias, 
                                    'part' => $i,
                                    'autostart' => 'true',
                                    '#' => 'play-movie'
                                )), 
                            'url_web_qs' => array(
                                'medium' => array(
                                    'name' => 'Trung Bình',
                                    'url_redirect' => Yii::app()->createAbsoluteUrl('/movie/movie/redirect', array(
                                            'year' => $this->year, 
                                            'alias' => $this->alias, 
                                            'server' => $alias, 
                                            'part' => $i,
                                            'q'    => 'medium',
                                        )),
                                    'url_web' => Yii::app()->createAbsoluteUrl('/movie/movie/view', array(
                                        'year' => $this->year, 
                                        'alias' => $this->alias, 
                                        'server' => $alias, 
                                        'part' => $i,
                                        'q'    => 'medium',
                                        'autostart' => 'true',
                                        '#' => 'play-movie'
                                    )),
                                ),
                                'large' => array(
                                    'name' => 'Tốt',
                                    'url_redirect' => Yii::app()->createAbsoluteUrl('/movie/movie/redirect', array(
                                            'year' => $this->year, 
                                            'alias' => $this->alias, 
                                            'server' => $alias, 
                                            'part' => $i,
                                            'q'    => 'large',
                                        )),
                                    'url_web' => Yii::app()->createAbsoluteUrl('/movie/movie/view', array(
                                        'year' => $this->year, 
                                        'alias' => $this->alias, 
                                        'server' => $alias, 
                                        'part' => $i,
                                        'q'    => 'large',
                                        'autostart' => 'true',
                                        '#' => 'play-movie'
                                    )),
                                ),
                                'hd720' => array(
                                    'name' => 'HD',
                                    'url_redirect' => Yii::app()->createAbsoluteUrl('/movie/movie/redirect', array(
                                            'year' => $this->year, 
                                            'alias' => $this->alias, 
                                            'server' => $alias, 
                                            'part' => $i,
                                            'q'    => 'hd720',
                                        )),
                                    'url_web' => Yii::app()->createAbsoluteUrl('/movie/movie/view', array(
                                        'year' => $this->year, 
                                        'alias' => $this->alias, 
                                        'server' => $alias, 
                                        'part' => $i,
                                        'q'    => 'hd720',
                                        'autostart' => 'true',
                                        '#' => 'play-movie'
                                    )),
                                ),


                            )  
                        ); 
                        $i++;   
                    }   
                }else{
                    foreach($server->links as $episode => $links){
                        foreach($links as $part => $link){
                            $data[$alias]['links'][$episode.$part] = $link;    
                        }   
                    }  
                }     
            }
            return $data;
        }


        public function reIndex(){
            set_time_limit(99999);
            Yii::import('application.vendors.*');
            require_once('Zend/Search/Lucene.php');
            $indexPath = 'application.runtime.search.movie';

            Yii::import('ext.TextParser');  
            $index = new Zend_Search_Lucene(Yii::getPathOfAlias($indexPath), true);
            Zend_Search_Lucene_Analysis_Analyzer::setDefault(new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8_CaseInsensitive());

            $movies = Movie::model()->findAll("is_enable = 1");
            foreach($movies as $movie){
                $doc = new Zend_Search_Lucene_Document();
                $doc->addField(Zend_Search_Lucene_Field::UnIndexed('movie_id', $movie->id));

                $doc->addField(Zend_Search_Lucene_Field::text('nameEncode', CHtml::encode($movie->name), 'utf-8'));
                $doc->addField(Zend_Search_Lucene_Field::text('name', CHtml::encode($movie->name), 'utf-8'));
                $doc->addField(Zend_Search_Lucene_Field::text('name_unsigned', CHtml::encode(TextParser::convertVietnameseToNon($movie->name)), 'utf-8'));

                $doc->addField(Zend_Search_Lucene_Field::text('name_en', CHtml::encode($movie->name_en), 'utf-8'));
                $doc->addField(Zend_Search_Lucene_Field::text('name_en_unsigned', CHtml::encode(TextParser::convertVietnameseToNon($movie->name_en)), 'utf-8'));

                $doc->addField(Zend_Search_Lucene_Field::text('actor', CHtml::encode($movie->actor), 'utf-8'));
                $doc->addField(Zend_Search_Lucene_Field::text('actor_unsigned', CHtml::encode(TextParser::convertVietnameseToNon($movie->actor)), 'utf-8'));

                $doc->addField(Zend_Search_Lucene_Field::text('director', CHtml::encode($movie->director), 'utf-8'));
                $doc->addField(Zend_Search_Lucene_Field::text('director_unsigned', CHtml::encode(TextParser::convertVietnameseToNon($movie->director)), 'utf-8'));

                $doc->addField(Zend_Search_Lucene_Field::keyword('year', $movie->year));

                $doc->addField(Zend_Search_Lucene_Field::text('desc', CHtml::encode($movie->desc), 'utf-8'));
                $doc->addField(Zend_Search_Lucene_Field::text('desc_unsigned', CHtml::encode(TextParser::convertVietnameseToNon($movie->desc)), 'utf-8'));



                //$doc->addField(Zend_Search_Lucene_Field::text('content', CHtml::encode($movie->content), 'utf-8'));
                //$doc->addField(Zend_Search_Lucene_Field::text('content_unsigned', CHtml::encode(TextParser::convertVietnameseToNon($movie->content)), 'utf-8'));


                $doc->addField(Zend_Search_Lucene_Field::unIndexed('is_hd', $movie->is_hd));
                $doc->addField(Zend_Search_Lucene_Field::unIndexed('url', $movie->url, 'utf-8'));
                $doc->addField(Zend_Search_Lucene_Field::unIndexed('imageThumbUrl', $movie->imageThumbUrl));
                $doc->addField(Zend_Search_Lucene_Field::unIndexed('imageUrl', $movie->imageUrl));
                $doc->addField(Zend_Search_Lucene_Field::unIndexed('catLinks', $movie->catLinks, 'utf-8'));
                $doc->addField(Zend_Search_Lucene_Field::unIndexed('view', $movie->view));

                $index->addDocument($doc);
            }
            $index->commit();
        }
}